package com.gitee.sidihuo.platform.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class RedisLockUtils {

    @Value("${app.env}")
    private String env;

    @Autowired(required = false)
    private RedisTemplate<String, Object> redisTemplate;

    public String buildKey(String key) {
        return env + "redis_lock_" + key;
    }


    public boolean lock(String key, String value, Long expireTimeSeconds) {
        if (null == expireTimeSeconds) {
            expireTimeSeconds = 60L;
        }
        String buildKey = buildKey(key);
        final boolean result = Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(buildKey, value, expireTimeSeconds, TimeUnit.SECONDS));
        if (result) {
            log.info("[redisTemplate redis]获得锁 缓存  key:{} ", key);
        }
        return result;
    }


    public boolean unlock(String key) {
        String buildKey = buildKey(key);
        final boolean result = Boolean.TRUE.equals(redisTemplate.delete(buildKey));
        if (result) {
            log.info("[redisTemplate redis]释放锁 缓存  key:{}", key);
        }
        return result;
    }

}
